//
//  HXHelper.m
//  HYTest
//
//  Created by 刘林欣 on 16/7/24.
//  Copyright © 2016年 刘林欣. All rights reserved.
//

#import "HXHelper.h"

@implementation HXHelper
{
//  标识是否正在调用注册，防止多次调用注册
    bool isRegisterring;
//  放所有需要监听环信事件的delegate
    NSMutableArray* hxListeners;
}

static HXHelper* hxHelper;

+ (HXHelper*)getInstance
{
    if(!hxHelper){
        hxHelper = [[HXHelper alloc] init];
        [hxHelper initEMSDK];//初始化环信SDK
    }
    return hxHelper;
}

- (void)register:(NSString*)uname pwd:(NSString*)pwd cb:(void(^)(NSMutableDictionary* result))cb
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = [[EMClient sharedClient] registerWithUsername:uname password:pwd];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSMutableDictionary* result = [self getReqResult:@"注册成功" error:error];
            cb(result);
        });
    });
}
- (void)login:(NSString*)uname pwd:(NSString*)pwd cb:(void(^)(NSMutableDictionary* result))cb
{
//    判断是否有自动登录，暂且不需要该操作，因为只要监听到自动登录成功，应用则不需要进入登录界面
//    BOOL isAutoLogin = [EMClient sharedClient].options.isAutoLogin;
//    if (!isAutoLogin) {
//        EMError *error = [[EMClient sharedClient] loginWithUsername:@"8001" password:@"111111"];
//    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = [[EMClient sharedClient] loginWithUsername:uname password:pwd];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSMutableDictionary* result = [self getReqResult:@"登录成功" error:error];
//          登录成功需要做的操作
            if([[result valueForKey:HXReqSuccessKey] boolValue]){
                [[EMClient sharedClient].options setIsAutoLogin:YES];
            }
            cb(result);
        });
    });
}
//根据error获取请求结果
- (NSMutableDictionary*)getReqResult:(NSString*)successStr error:(EMError*)error
{
    NSMutableDictionary* result = [NSMutableDictionary dictionary];
    if (!error) {
        [result setValue:@true forKey:HXReqSuccessKey];
        [result setValue:successStr forKey:HXReqInfoKey];
    }else{
        NSString* errorStr = [self getErrorMsg:error];
        [result setValue:@false forKey:HXReqSuccessKey];
        [result setValue:errorStr forKey:HXReqInfoKey];
    }
    return result;
}
//获取请求错误的中文解释
- (NSString*)getErrorMsg:(EMError *)error
{
    NSString* errorStr = @"";
    switch (error.code) {
        case EMErrorServerNotReachable:
            errorStr = @"无法连接服务器";
            break;
        case EMErrorUserAlreadyExist:
            errorStr = @"您注册的用户名已存在";
            break;
        case EMErrorNetworkUnavailable:
            errorStr = @"没有网络";
            break;
        case EMErrorServerTimeout:
            errorStr = @"请求超时";
            break;
        case EMErrorUserAuthenticationFailed:
            errorStr = @"用户名或密码错误";
            break;
        default:
            errorStr = @"请求失败，未知错误";
            break;
    }
    return errorStr;
}

//应用进入后台
- (void)appDidEnterBg:(UIApplication *)application
{
    [[EMClient sharedClient] applicationDidEnterBackground:application];
}
//应用激活
- (void)appWillEnterFg:(UIApplication *)application
{
    [[EMClient sharedClient] applicationWillEnterForeground:application];
}

//初始化环信SDK
- (void)initEMSDK
{
//    初始化变量
    isRegisterring = false;
    hxListeners = [NSMutableArray array];
    
    //AppKey:注册的AppKey，详细见下面注释。
    //apnsCertName:推送证书名（不需要加后缀），详细见下面注释。
    EMOptions *options = [EMOptions optionsWithAppkey:EaseMobAppKey];
    NSString *apnsCertName = nil;
#if DEBUG
    apnsCertName = EaseMobApnsDevCert;
#else
    apnsCertName = EaseMobApnsProCert;
#endif
    options.apnsCertName = apnsCertName;
//  这个调用顺序不知道能不能监听到自动登录结果
    [[EMClient sharedClient] initializeSDKWithOptions:options];
    
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].groupManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].contactManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].roomManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
}

- (void)addDelegate:(id<HXHelperDelegate>)delegate
{
    bool haveTheDelegate = false;
    for(id<HXHelperDelegate>d in hxListeners){
        if(d == delegate){
            haveTheDelegate = true;
            break;
        }
    }
//  如果没有该delegate才添加
    if(!haveTheDelegate){
        [hxListeners addObject:delegate];
    }
}
- (void)removeDelegate:(id<HXHelperDelegate>)delegate
{
    for(id<HXHelperDelegate>d in hxListeners){
        if(d == delegate){
            [hxListeners removeObject:d];
            break;
        }
    }
}

- (void)didLoginFromOtherDevice
{
    for(id<HXHelperDelegate>d in hxListeners){
//      判断该delegate是否有该方法
        if([d respondsToSelector:@selector(didLoginFromOtherDevice)]){
            [d didLoginFromOtherDevice];
        }
    }
}

@end
